package cn.wen233.srpc.core.service.spi;

import cn.wen233.srpc.core.execute.ClientExecutor;
import cn.wen233.srpc.core.execute.client.SerializeClientExecutor;
import cn.wen233.srpc.core.utils.ServiceLoaderUtils;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SPI 机制Context
 *
 * @author wenei
 * @date 2021-12-27 22:56
 */
public class SPIContext {

    private static final Map<Class<?>, List<?>> cache = new HashMap<>();

    /**
     * 返回所有tClass的实例，
     * 并通过Order大小升序排序
     */
    public static <T> List<T> loadService(Class<T> tClass) {
        if (cache.get(tClass) != null) {
            return (List<T>) cache.get(tClass);
        }
        List<T> loaderClassInstance = ServiceLoaderUtils.getLoaderClassInstance(tClass);
        Comparator<T> comparator = Comparator.comparingInt(o -> orderValue(o.getClass()));
        loaderClassInstance.sort(comparator);
        cache.put(tClass, loaderClassInstance);
        return loaderClassInstance;
    }

    /**
     * 取最前面的一个实例
     */
    public static <T> T loadSingleService(Class<T> tClass) {
        List<T> loadService = loadService(tClass);
        if (loadService == null || loadService.isEmpty()) {
            throw new IllegalArgumentException(String.format("没有指定的%s类通过SPI方式注入", tClass.getName()));
        }
        return loadService.get(0);
    }

    private static int orderValue(Class<?> tClass) {
        Order order = tClass.getDeclaredAnnotation(Order.class);
        if (order == null) {
            return 0;
        }
        return order.value();
    }
}
